import inspect
import json
import logging
import math
import os.path
from typing import List, Dict, Type

from fastapi import APIRouter, BackgroundTasks, UploadFile, Depends, Form, File, Query, HTTPException
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel, model_validator
from sentence_transformers import SentencesDataset, SentenceTransformer, losses
from sentence_transformers.evaluation import EmbeddingSimilarityEvaluator
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import Session
from starlette import status
from starlette.responses import JSONResponse
from starlette.websockets import WebSocket

from torch.utils.data import DataLoader

from api.database.curd import get_sample, create_sample_entity, sample_list
from api.database.database import SessionLocal, get_db
from api.database.models import SampleEntity
from api.utils import sample_path, rootpath, ErrorResponse

# 用于样本训练
router = APIRouter()


# 获取样本信息列表;
@router.get('/list', description='获取所有的样本详细信息')
async def sample_list_post(user_name: str = Query(None, title="单位或者用户名", description="如果不填，查询所有样本"),
                           db: Session = Depends(get_db)):
    samples = sample_list(db, user_name)
    if not samples:
        return JSONResponse(content={"message": ""}, status_code=status.HTTP_200_OK)
    items_json = jsonable_encoder(samples)
    return JSONResponse(content={"message": json.dumps(items_json)}, status_code=status.HTTP_200_OK)


# 删除样本
@router.post('/del', description='根据样本名和用户名删除样本')
async def sample_del(sample_name: str, user_name: str, db: Session = Depends(get_db)):
    # 删除样本;
    return {'hello': 'world'}


class SampleItem(BaseModel):
    sample_name: str
    user_name: str


@router.post('/upload')
async def sample_upload(file: UploadFile, item: str = Form(), db: Session = Depends(get_db)):
    item_json = json.loads(item)
    sample_item = SampleItem(**item_json)
    if len(sample_item.sample_name) == 0:
        return JSONResponse(content={"message": "样例名不可为空"}, status_code=status.HTTP_400_BAD_REQUEST)

    file_path = os.path.join(sample_path(), sample_item.user_name)
    if not os.path.exists(file_path):
        os.makedirs(file_path)
    file_path = os.path.join(file_path, file.filename)
    context = await file.read()
    with open(file_path, "wb") as buffer:
        buffer.write(context)

    releave_path = os.path.relpath(file_path, rootpath())
    # 写完文件更新数据库;
    sample_entity = SampleEntity(**sample_item.dict())
    sample_entity.path = releave_path
    create_sample_entity(db, sample_entity)
    return JSONResponse(content={"message": "ok"}, status_code=status.HTTP_200_OK)



